var express = require('express');
var router = express.Router();
const { UserModel } = require('../db/index');
const mongoose = require('mongoose');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 通过_id查找用户，如果提供了username则更新
router.post('/newUser', async function(req, res) {
  const { _id, username } = req.body;

  if (!_id) {
    return res.status(400).json({ code: 1, msg: '请求中缺少 _id 参数' });
  }

  try {
    if (!mongoose.Types.ObjectId.isValid(_id)) {
      return res.status(400).json({ code: 1, msg: '_id 格式无效' });
    }

    const updatedUser = await UserModel.findByIdAndUpdate(
      _id,
      { 
        $set: { userName: username },
        $setOnInsert: { money: 1000, userName: username || `用户-${_id.slice(-4)}` }
      },
      { new: true, upsert: true, setDefaultsOnInsert: true }
    ).lean();
    
    res.json({ code: 0, data: updatedUser });

  } catch (err) {
    console.error('[/lyx/newUser] 接口在数据库操作时出现严重错误:', err);
    res.status(500).json({ code: 1, msg: '数据库操作失败', error: err.message });
  }
});

module.exports = router;
